package com.test.javafaq_portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.test.javafaq_portal.entity.*;
import com.test.javafaq_portal.mapper.QuestionMapper;
import com.test.javafaq_portal.mapper.QuestionTagMapper;
import com.test.javafaq_portal.mapper.UserMapper;
import com.test.javafaq_portal.mapper.UserQuestionMapper;
import com.test.javafaq_portal.service.IQuestionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.javafaq_portal.service.ITagService;
import com.test.javafaq_portal.service.IUserService;
import com.test.javafaq_portal.service.ServiceException;
import com.test.javafaq_portal.vo.QuestionVo;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author test.com
 * @since 2025-04-11
 */
@Service
@Slf4j
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {

    @Autowired
    IUserService userService;
    @Autowired
    UserMapper userMapper;

    @Autowired
    QuestionMapper questionMapper;

    @Autowired
    ITagService tagService;

    @Autowired
    QuestionTagMapper questionTagMapper;

    @Autowired
    UserQuestionMapper userQuestionMapper;

    @Override
    public Question getQuestionById(Integer id) {
        Question question = questionMapper.selectById(id);
        List<Tag> tags = tagNamesToTags(question.getTagNames());
        question.setTags(tags);
        return question;
    }

    @Override
    public Integer countQuestionByUserId(Integer userId) {
        QueryWrapper<Question> query = new QueryWrapper<>();
        query.eq("user_id",userId);
        query.eq("delete_status",0);
        Integer count = questionMapper.selectCount(query);
        return count;
    }

    @Override
    @Transactional //此方法所有数据库操作定义为一个事务
    public void saveQuestion(QuestionVo questionVo) {
        //获取登陆用户信息
        String username = userService.currentUsername();
        User u = userMapper.findUserByUsername(username);
        log.debug("获取用户信息：{}",u);
        //将标签转化成字符串存储到  tag_names
        StringBuilder buf = new StringBuilder();
        for (String tagName : questionVo.getTagNames()) {
            buf.append(tagName).append(",");
        }
        //去掉最后的,号
        String tagNames = buf.deleteCharAt(buf.length() - 1).toString();
        //question实体的创建和收集
        Question question = new Question()
                .setTitle(questionVo.getTitle())
                .setContent(questionVo.getContent())
                .setUserNickName(u.getNickname())
                .setUserId(u.getId())
                .setCreatetime(LocalDateTime.now())
                .setStatus(0)
                .setPageViews(0)
                .setPublicStatus(0)
                .setDeleteStatus(0)
                .setTagNames(tagNames);
        //执行 question的新增
        int num = questionMapper.insert(question);
        if(num != 1){
            throw ServiceException.busy();
        }
        log.debug("新增question完成：{}",question);
        //新增问题和标签的关联
        Map<String, Tag> name2TagMap = tagService.getName2TagMap();
        for (String tagName : questionVo.getTagNames()) {
            Tag tag = name2TagMap.get(tagName);
            QuestionTag questionTag = new QuestionTag()
                    .setQuestionId(question.getId())
                    .setTagId(tag.getId());
            num = questionTagMapper.insert(questionTag);
            if(num != 1){
                throw ServiceException.busy();
            }
        }
        log.debug("新增questionTag完成：---------------");
        //新增问题和老师的关联
        Map<String, User> teachersMap = userService.getTeachersMap();
        for (String nickname : questionVo.getTeacherNicknames()) {
            User user = teachersMap.get(nickname);
            UserQuestion userQuestion = new UserQuestion()
                    .setUserId(user.getId())
                    .setQuestionId(question.getId())
                    .setCreatetime(LocalDateTime.now());
            num = userQuestionMapper.insert(userQuestion);
            if(num != 1){
                throw ServiceException.busy();
            }
        }
        log.debug("新增老师和问题关联完成：---------------");
    }

    @Override
    //public List<Question> getMyQuestions() {
    public PageInfo<Question> getMyQuestions(Integer pageNum,Integer pageSize) {
        if(pageNum == null || pageSize==null){
            throw ServiceException.invalidRequest("缺失分页参数!");
        }

        //获取当前登陆用户姓名
        String username = userService.currentUsername();
        //根据用户姓名获取对象
        User u = userMapper.findUserByUsername(username);
        if(u == null){
            throw ServiceException.gone("登陆用户不存在");
        }
        //根据用户id查询这个学生的问题   delete_status=0 未删除    user_id
        QueryWrapper<Question> query = new QueryWrapper<>();
        query.eq("user_id",u.getId());
        query.eq("delete_status",0);
        query.orderByDesc("createtime");
        //设置分页 信息
        PageHelper.startPage(pageNum,pageSize);

        List<Question> list = questionMapper.selectList(query);
        //为了显示每个问题的标签添加代码如下：
        for(Question q:list){
            List<Tag> tags = tagNamesToTags(q.getTagNames());
            q.setTags(tags);
        }
        //返回所有问题
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<Question> getTeacherQuestions(String name, Integer pageNum, Integer pageSize) {
        if(pageNum == null || pageSize==null){
            throw ServiceException.invalidRequest("缺失分页参数!");
        }
        PageHelper.startPage(pageNum,pageSize);
        User teacherId = userMapper.findUserByUsername(name);
        List<Question> teacherQuestions = userQuestionMapper.findTeacherQuestions(teacherId.getId());
        for(Question q:teacherQuestions){
            List<Tag> tags = tagNamesToTags(q.getTagNames());
            q.setTags(tags);
        }
        return new PageInfo<Question>(teacherQuestions);
    }

    //编写一个方法，这个方法能将tagNames字符串返回为List<Tag>
    private List<Tag> tagNamesToTags(String tagNames){
        //tagNames="Java基础,SpringCloud"
        String[] names = tagNames.split(",");
        // names = {"Java基础","SpringCloud"}
        List<Tag> tags = new ArrayList<>();
        //遍历所有names，获取对应元素的tag对象，保存奥list中
        Map<String, Tag> map = tagService.getName2TagMap();
        for (String tagName:names){
            Tag tag = map.get(tagName);
            tags.add(tag);
        }
        return tags;
    }


}
